package com.shop.cereshop.app.job;

import cn.hutool.core.collection.CollUtil;
import com.shop.cereshop.app.tencent.im.model.redpacket.RedPacket;
import com.shop.cereshop.app.tencent.im.model.transfer.TransferOrder;
import com.shop.cereshop.app.tencent.im.service.RedPacketService;
import com.shop.cereshop.app.tencent.im.service.TransferOrderService;
import com.shop.cereshop.commons.enums.RefundTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description: 订单补偿检查定时任务（兜底）
 * @author zdd
 * @date 2025/9/13 13:24
 * @version 1.0
 */
@Component
@Slf4j
public class OrderExpiredCompensationJob {

    @Resource
    private RedPacketService redPacketService;
    @Resource
    private TransferOrderService transferOrderService;

    /**
     * 红包过期未领取自动取消并退款
     * 每天凌晨3点检查漏单
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void redPacketCompensation() {
        log.info("开始执行【红包】过期未领取补偿检查...");
        List<RedPacket> packets = redPacketService.getExpiredRedPackets();
        log.info("检查到{}个【红包】已过期未领取", packets.size());
        if (CollUtil.isEmpty( packets)) {
            return;
        }
        for (RedPacket packet : packets) {
            redPacketService.refund(packet.getPacketId());
            redPacketService.modifyTimMsg(packet.getPacketId());
        }
        log.info("【红包】过期未领取补偿检查完成！");
    }

    /**
     * 转账订单过期未领取自动取消并退款
     * 每天凌晨3点检查漏单
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void dailyCompensation() {
        log.info("开始执行【转账订单】过期未领取补偿检查...");
        List<TransferOrder> transferOrders = transferOrderService.getExpiredTransferOrders();
        log.info("检查到{}个【转账订单】已过期未领取", transferOrders.size());
        if (CollUtil.isEmpty(transferOrders)) {
            return;
        }
        for (TransferOrder transferOrder : transferOrders) {
            transferOrderService.refund(transferOrder.getTransferId(), RefundTypeEnum.EXPIRED.getCode());
            transferOrderService.modifyTimMsg(transferOrder.getTransferId());
        }
        log.info("【转账订单】过期未领取补偿检查完成！");
    }

}
